<template>
  <div class="page-fs">
    <el-row>
      <el-col :span="8">
        <a-input
          v-model="wsUrl"
          placeholder="请输入ws地址"
          style=""
        />
      </el-col>
      <el-col
        :span="16"
        style="text-align: left; padding-left: 20px;"
      >
        <a-button @click="connWs">
          链接
        </a-button>
      </el-col>
    </el-row>
    <el-image :src="imgSrc" />
  </div>
</template>

<script>
import UtilStream from "@/util/util-stream";
let vueObj
export default {
  data() {
    return {
      imgSrc: "",
      wsUrl: ""
    }
  },
  mounted() {
    vueObj = this
  },
  methods: {
    connWs() {
      if (this.wsUrl && this.wsUrl.length > 0) {
        initWs(this.wsUrl)
      }
    }
  }
}

let webSocket

function initWs(wsUrl) {
  if (webSocket) {
    webSocket.close()
  }
  webSocket = new WebSocket(wsUrl)
  webSocket.onmessage = wsOnMessage
  webSocket.onopen = wsOnOpen
  webSocket.onerror = wsOnError
  webSocket.onclose = wsOnClose

  function wsOnMessage(msg) {
    console.log(msg)
    let res = JSON.parse(msg.data)
    res = UtilStream.hex2Bytes(res.PKD)
    res = UtilStream.bytesToBase64(res)
    res = UtilStream.buildBase64Url(res)
    console.log(res)
    vueObj.imgSrc = res
  }
  function wsOnOpen() {
    console.log('websocket connect success!')
    webSocket.send(JSON.stringify({"test":"12345"}))
  }
  function wsOnError(e) {
    console.log('websocket connect error - ', e)
  }
  function wsOnClose() {

  }
}
</script>

<style scoped>

</style>